package com.leetcodehot.problems;

import java.util.ArrayList;
import java.util.List;

public class problems530 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 暴力做法
     */
    /*
    private List<Integer> list = new ArrayList<>();

    public int getMinimumDifference(TreeNode root) {
        dfs(root);
        list.sort(Integer::compareTo);
        int min = Integer.MAX_VALUE;
        for (int i = 1; i < list.size(); i++) {
            min = Math.min(min, list.get(i) - list.get(i - 1));
        }
        return min;
    }

    private void dfs(TreeNode root) {
        if (root == null) return;
        list.add(root.val);
        dfs(root.left);
        dfs(root.right);
    }*/
    private Integer min = Integer.MAX_VALUE;
    private Integer pre = Integer.MIN_VALUE;

    private void dfs(TreeNode root) {
        if (root == null) return;
        dfs(root.left);
        int x = root.val;
        if (pre < 0) {
            pre = x;
        } else {
            min = Math.min(min, Math.abs(x - pre));
        }
        pre = x;
        dfs(root.right);
    }

    public int getMinimumDifference(TreeNode root) {
        dfs(root);
        return min;
    }
}
